package com.tmt.im.manager.service;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.data.jpa.service.TmtJpaDataService;
import com.tmt.data.jpa.service.beans.RoleAuthorityInfoVo;
import com.tmt.data.jpa.service.beans.SyncRoleAuthorityDataResponse;
import com.tmt.im.jpa.entity.IMAuthority;
import com.tmt.im.jpa.entity.IMRole;
import com.tmt.im.jpa.entity.IMRoleAuthority;
import com.tmt.im.jpa.repository.IMAuthorityRepo;
import com.tmt.im.jpa.repository.IMRoleAuthorityRepo;
import com.tmt.im.jpa.repository.IMRoleRepo;
import com.tmt.im.manager.config.beans.DataSyncProperties;
import com.tmt.springboot.common.restful.ExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/20 11:53
 * @Version 1.0
 **/
@Slf4j
@Service
@Order(5)
public class IMRoleAuthorityService extends TmtJpaDataService<IMRoleAuthority, Long> {

    private final IMRoleAuthorityRepo roleAuthorityRepo;

    private final IMRoleRepo roleRepo;

    private final IMAuthorityRepo authorityRepo;

    private final DataSyncProperties dataSyncProperties;

    public IMRoleAuthorityService(IMRoleAuthorityRepo mainRepo,
                                  IMRoleRepo roleRepo,
                                  IMAuthorityRepo authorityRepo,
                                  DataSyncProperties dataSyncProperties) {
        super(mainRepo);
        this.roleAuthorityRepo = mainRepo;
        this.roleRepo = roleRepo;
        this.authorityRepo = authorityRepo;
        this.dataSyncProperties = dataSyncProperties;
    }

    @Transactional(rollbackFor = Exception.class)
    public void InitializeTable() {
        try {
            log.info("----从授权服务器拉取角色权限列表----开始---");
            loadRoleAuthorities();
            log.info("----从授权服务器拉取角色权限列表----结束---");
        } catch (Exception ex) {
            log.debug(ex.getMessage(), ex);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void loadRoleAuthorities() {
        long pageIndex = 0;
        Long totalPageCount = null;

        JSONObject request = new JSONObject();
        request.put("pageIndex", pageIndex);
        request.put("pageSize", 50);
        request.put("clientId", null);

        while (totalPageCount == null || pageIndex < totalPageCount) {
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request);
            ParameterizedTypeReference<ExecuteResult<SyncRoleAuthorityDataResponse>> responseType = new ParameterizedTypeReference<>() {
            };
            ResponseEntity<ExecuteResult<SyncRoleAuthorityDataResponse>> jsonObjectResponseEntity =
                    new RestTemplate().exchange(dataSyncProperties.getRoleAuthorityDataUrl(), HttpMethod.POST, entity, responseType);

            ExecuteResult<SyncRoleAuthorityDataResponse> body = jsonObjectResponseEntity.getBody();
            assert body != null;
            if (body.getData() == null || CollectionUtils.isEmpty(body.getData().getRoleAuthorityInfoVos())) {
                return;
            }
            try {
                for (RoleAuthorityInfoVo vo : body.getData().getRoleAuthorityInfoVos()) {
                    try {
                        IMRole role = roleRepo.findById(vo.getRoleId()).orElse(null);
                        assert role != null;
                        IMAuthority authority = authorityRepo.findById(vo.getAuthorityId()).orElse(null);
                        assert authority != null;
                        IMRoleAuthority roleAuthority = roleAuthorityRepo.findById(vo.getId()).orElse(null);
                        if (roleAuthority != null) {
                            roleAuthority.setAuthority(authority);
                            roleAuthority.setRole(role);
                        } else {
                            roleAuthority = new IMRoleAuthority();
                            roleAuthority.setId(vo.getId());
                            roleAuthority.setAuthority(authority);
                            roleAuthority.setRole(role);
                        }
                        roleAuthorityRepo.save(roleAuthority);
                    } catch (Exception ex) {
                        log.error("导入角色权限数据出现异常：{}", ex.getMessage());
                    }
                }
                if (totalPageCount == null) {
                    totalPageCount = body.getData().getTotalPages();
                }
                pageIndex++;
                request.put("pageIndex", pageIndex);
            } catch (Exception ex) {
                log.error("接口{}返回的数据格式异常:{}", dataSyncProperties.getRoleAuthorityDataUrl(), body);
            }
        }

    }
}
